﻿namespace BEGDC.CC.Web.UserControls.CR
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Collections;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.BL.CCFlow.CR;
    using BEGDC.CC.BL.CCFlow.CV;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.Utility.Castle;

    /// <summary>
    ///		Summary description for Summary.
    /// </summary>
    public class CRSurvey : BaseCR
    {
        #region Variables
        protected System.Web.UI.WebControls.Button Btn_Save;
        protected System.Web.UI.WebControls.Button Btn_Reject;
        protected System.Web.UI.WebControls.TextBox Ctl_CompanyName;
        protected System.Web.UI.WebControls.TextBox Ctl_Date;
        protected System.Web.UI.HtmlControls.HtmlImage SurveyDateImg;
        protected System.Web.UI.WebControls.TextBox Ctl_VisitObj;
        protected System.Web.UI.WebControls.TextBox Ctl_TravelAgency;
        protected System.Web.UI.WebControls.TextBox Ctl_VI;
        protected System.Web.UI.WebControls.TextBox Ctl_Persons;
        protected System.Web.UI.WebControls.DataGrid DG_PartB;
        protected System.Web.UI.WebControls.DataGrid DG_PartA;
        protected System.Web.UI.WebControls.Label Lb_ScoreA;
        protected System.Web.UI.WebControls.Label Lb_ScoreB;
        protected System.Web.UI.WebControls.Button Btn_Submit;
        protected System.Web.UI.WebControls.TextBox tbScoreA;
        protected System.Web.UI.WebControls.TextBox tbScoreB;
        protected System.Web.UI.WebControls.TextBox tbScoreARowCount;
        protected System.Web.UI.WebControls.TextBox tbScoreBRowCount;
        protected System.Web.UI.HtmlControls.HtmlTableRow tr_Title;
        protected System.Web.UI.WebControls.Label Label1;
        protected System.Web.UI.WebControls.Button Btn_Reply;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected bool IsFeedbackStep = true;
        #endregion

        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }

        //		protected bool BeginFeedback
        //		{
        //			get
        //			{
        //				IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
        //				return queryService.BeginFeedback( this.AppID );
        //			}
        //		}

        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }


        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!this.IsPostBack)
            {
                base.PreInitForm();

                this.Btn_Save.Attributes["onclick"] = "javascript:OnSave();";
                this.Btn_Submit.Attributes["onclick"] = "javascript:OnSubmit();";
                this.Btn_Reply.Attributes.Add("onclick", "javascript:OpenCommentPane();");

                InitForm();
                ButtonStatusSetting();

                //				if( this.Step != BEGDC.CC.BL.Workflow.WorkTransition.CV_Feedback || this.IsView || !this.BeginFeedback)
                //				{
                //					IsFeedbackStep = false;
                //					BindReadOnlyStatus();
                //				}
                //Check Access
                //Accessibility access = this.CheckAccessibility(WorkTransition.CR_CRSurvey, BEGDC.CC.BL.Workflow.UserRole.CRApplicant);
                //ControlStatusSetting( access );
            }
        }


        private void BindReadOnlyStatus()
        {
            //this.Label1.Text = string.Empty;
            this.Btn_Save.Visible = false;
            this.Btn_Submit.Visible = false;
            this.Ctl_VisitObj.Enabled = false;
            this.Ctl_TravelAgency.Enabled = false;
            this.Ctl_VI.Enabled = false;
            this.Ctl_Persons.Enabled = false;
            //			this.Ctl_Score.Enabled = false;

            foreach (DataGridItem row in this.DG_PartA.Items)
            {
                DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
                TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentA");

                Dp_Score.Enabled = false;
                Tx_Comment.Enabled = false;
            }

            foreach (DataGridItem row in this.DG_PartB.Items)
            {
                DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
                TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentB");

                Dp_Score.Enabled = false;
                Tx_Comment.Enabled = false;
            }

            if (this.IsView)
                tr_Title.Visible = false;
        }


        #region IsAfterEndDate
        private bool IsAfterEndDate(string RequestedEndDate)
        {
            DateTime Currenttime = DateTime.Now;
            DateTime EndDate = Convert.ToDateTime(RequestedEndDate);
            if (Currenttime > EndDate)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region ControlStatusSetting
        private void ControlStatusSetting(Accessibility access)
        {
            if (access == Accessibility.Readonly)
            {
                this.DisableChildrenControls(this);
                //this.stampCtrl1.Visible = false;
            }
        }
        #endregion

        #region InitForm
        private void InitForm()
        {
            bool isReadOnly = true;
            long flowId = this.LoadApplication();

            if (this.Application != null)
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;

                //Customer Survey
                BEGDC.CC.Entity.CustomerSurvey survey = CRService.GetCustomerSurvey(this.Application.Id);

                if (survey != null)
                {
                    this.Ctl_VisitObj.Text = survey.VisitObjective;
                    this.Ctl_TravelAgency.Text = survey.TravelAgency;
                    this.Ctl_VI.Text = survey.Itinerary;
                    this.Ctl_Persons.Text = survey.NumberOfPerson;
                    this.tbScoreA.Text = survey.ScoreA.ToString();
                    this.tbScoreB.Text = survey.ScoreB.ToString();
                }

                //BIND PART_A QUESTIONS
                DataTable PartA = CRService.GetSurveyQuestions(BEGDC.CC.BL.Workflow.WorkflowTypes.CR, "PartA-Visit", true);
                if (PartA != null && PartA.Rows.Count > 0)
                {
                    this.DG_PartA.DataSource = PartA;
                    this.DG_PartA.DataBind();
                    this.tbScoreARowCount.Text = PartA.Rows.Count.ToString();
                }

                //BIND PART_B QUESTIONS
                DataTable PartB = CRService.GetSurveyQuestions(BEGDC.CC.BL.Workflow.WorkflowTypes.CR, "PartB-Reception", true);
                if (PartB != null && PartB.Rows.Count > 0)
                {
                    this.DG_PartB.DataSource = PartB;
                    this.DG_PartB.DataBind();
                    this.tbScoreBRowCount.Text = PartB.Rows.Count.ToString();
                }

                if (survey != null)
                {
                    DataTable AnswerTable = CRService.GetSurveyAnswer(survey.Id);
                    if (AnswerTable != null && AnswerTable.Rows.Count > 0)
                    {
                        DoBindAnswersA(this.DG_PartA, AnswerTable);
                        DoBindAnswersB(this.DG_PartB, AnswerTable);
                    }
                }

                //				if(!BeginFeedback())
                //				{
                //					WebUtility.DisableChildrenControls(this);
                //				}
            }
        }
        #endregion

        #region Do Bind Answers
        private void DoBindAnswersA(DataGrid datagrid, DataTable AnswerTable)
        {
            DataRow AnsRow = null;
            foreach (DataGridItem row in datagrid.Items)
            {
                string QuestionID = row.Cells[0].Text.ToString();
                AnsRow = SearchDataTable(AnswerTable, QuestionID);
                if (AnsRow != null)
                {
                    DropDownList Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
                    TextBox Comment = (TextBox)row.FindControl("Ctl_CommentA");
                    if (AnsRow["Score"] != null || AnsRow["Score"].ToString() != "")
                    {
                        Score.SelectedIndex = Score.Items.IndexOf(Score.Items.FindByValue(AnsRow["Score"].ToString()));
                    }
                    Comment.Text = AnsRow["Comment"].ToString();
                }
            }
        }
        private void DoBindAnswersB(DataGrid datagrid, DataTable AnswerTable)
        {
            DataRow AnsRow = null;
            foreach (DataGridItem row in datagrid.Items)
            {
                string QuestionID = row.Cells[0].Text.ToString();
                AnsRow = SearchDataTable(AnswerTable, QuestionID);
                if (AnsRow != null)
                {
                    DropDownList Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
                    TextBox Comment = (TextBox)row.FindControl("Ctl_CommentB");
                    if (AnsRow["Score"] != null || AnsRow["Score"].ToString() != "")
                    {
                        Score.SelectedIndex = Score.Items.IndexOf(Score.Items.FindByValue(AnsRow["Score"].ToString()));
                    }
                    Comment.Text = AnsRow["Comment"].ToString();
                }
            }
        }

        private DataRow SearchDataTable(DataTable table, string Id)
        {
            if (table != null)
            {
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if ((table.Rows[i]["QuestionId"].ToString()) == Id)
                    {
                        return table.Rows[i];
                    }
                }
            }
            return null;
        }
        #endregion

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.Btn_Save.Click += new EventHandler(Btn_Save_Click);
            this.Btn_Submit.Click += new EventHandler(Btn_Submit_Click);
            this.Btn_Reply.Click += new EventHandler(Btn_Reply_Click);
            this.Load += new System.EventHandler(this.Page_Load);
        }
        #endregion

        #region BUILD SURVEY DATA
        public BEGDC.CC.Entity.CustomerSurvey BuildCustomerSurvey()
        {
            if (this.AppID == 0 || this.Application == null) return null;

            ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
            BEGDC.CC.Entity.CustomerSurvey survey = CRService.GetCustomerSurvey(this.AppID);

            if (survey == null)
            {
                survey = new BEGDC.CC.Entity.CustomerSurvey();
                survey.Id = 0;
                survey.Application = this.Application;
            }

            survey.VisitObjective = this.Ctl_VisitObj.Text;
            survey.TravelAgency = this.Ctl_TravelAgency.Text;
            survey.Itinerary = this.Ctl_VI.Text;
            survey.NumberOfPerson = this.Ctl_Persons.Text;
            survey.ScoreA = Convert.ToDecimal(this.tbScoreA.Text);
            survey.ScoreB = Convert.ToDecimal(this.tbScoreB.Text);

            return survey;
        }

        private IList DoAnswerList(int SurveyId)
        {
            ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
            IList QuestionList = CRService.GetSurveyQuestionList();
            IList AnswerList = CRService.GetSurveyAnswerList(SurveyId);
            if (AnswerList == null)
            {
                AnswerList = new ArrayList();
            }

            if (this.DG_PartA.Items.Count > 0)
            {
                foreach (DataGridItem row in this.DG_PartA.Items)
                {
                    int QuestionId = Convert.ToInt32(row.Cells[0].Text.ToString());
                    DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
                    TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentA");

                    BEGDC.CC.Entity.SurveyAnswer sa = SearchArrayList(AnswerList, QuestionId);

                    if (sa == null)
                    {
                        sa = new BEGDC.CC.Entity.SurveyAnswer();
                        sa.SurveyQuestion = SearchQuestionList(QuestionList, QuestionId);
                        sa.Score = Dp_Score.SelectedValue.ToString();
                        sa.Comment = Tx_Comment.Text;
                        AnswerList.Add(sa);
                    }
                    else
                    {
                        sa.Score = Dp_Score.SelectedValue.ToString();
                        sa.Comment = Tx_Comment.Text;
                    }
                }
            }

            if (this.DG_PartB.Items.Count > 0)
            {
                foreach (DataGridItem row in this.DG_PartB.Items)
                {
                    int QuestionId = Convert.ToInt32(row.Cells[0].Text.ToString());
                    DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
                    TextBox Tx_Comment = (TextBox)row.FindControl("Ctl_CommentB");

                    BEGDC.CC.Entity.SurveyAnswer sa = SearchArrayList(AnswerList, QuestionId);

                    if (sa == null)
                    {
                        sa = new BEGDC.CC.Entity.SurveyAnswer();
                        sa.SurveyQuestion = SearchQuestionList(QuestionList, QuestionId);
                        sa.Score = Dp_Score.SelectedValue.ToString();
                        sa.Comment = Tx_Comment.Text;
                        AnswerList.Add(sa);
                    }
                    else
                    {
                        sa.Score = Dp_Score.SelectedValue.ToString();
                        sa.Comment = Tx_Comment.Text;
                    }
                }
            }
            return AnswerList;
        }

        private BEGDC.CC.Entity.SurveyAnswer SearchArrayList(IList AnswerList, int QuestionId)
        {
            if (AnswerList != null)
            {
                for (int i = 0; i < AnswerList.Count; i++)
                {
                    BEGDC.CC.Entity.SurveyAnswer sa = AnswerList[i] as BEGDC.CC.Entity.SurveyAnswer;
                    if (sa.SurveyQuestion.Id == QuestionId)
                    {
                        return sa;
                    }
                }
            }
            return null;
        }

        private BEGDC.CC.Entity.SurveyQuestion SearchQuestionList(IList QuestionList, int QuestionId)
        {
            if (QuestionList != null)
            {
                for (int i = 0; i < QuestionList.Count; i++)
                {
                    BEGDC.CC.Entity.SurveyQuestion sq = QuestionList[i] as BEGDC.CC.Entity.SurveyQuestion;
                    if (sq.Id == QuestionId)
                    {
                        return sq;
                    }
                }
            }
            return null;
        }

        private int CaculateScoreA(System.Web.UI.WebControls.DataGrid dataGrid)
        {
            int QuestionCount = 0;
            int Score = 0;
            foreach (DataGridItem row in dataGrid.Items)
            {
                QuestionCount++;
                DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
                Score += Convert.ToInt32(Dp_Score.SelectedValue.ToString());
            }

            if (QuestionCount > 0)
            {
                return Score / QuestionCount;
            }
            else
            {
                return 0;
            }
        }

        private int CaculateScoreB(System.Web.UI.WebControls.DataGrid dataGrid)
        {
            int QuestionCount = 0;
            int Score = 0;
            foreach (DataGridItem row in dataGrid.Items)
            {
                DropDownList Dp_Score = (DropDownList)row.FindControl("Ctrl_ScoreB");
                if (Dp_Score.SelectedItem.Value != "0")
                {
                    QuestionCount++;
                    Score += Convert.ToInt32(Dp_Score.SelectedValue.ToString());
                }
            }

            if (QuestionCount > 0)
            {
                return Score / QuestionCount;
            }
            else
            {
                return 0;
            }
        }
        #endregion

        #region Save
        void Btn_Save_Click(object sender, EventArgs e)
        {
            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                BEGDC.CC.Entity.CustomerSurvey survey = BuildCustomerSurvey();
                //survey.ScoreA = CaculateScoreA(this.DG_PartA);
                //survey.ScoreB = CaculateScoreB(this.DG_PartB);
                survey.ScoreA = Convert.ToDecimal(this.tbScoreA.Text);
                survey.ScoreB = Convert.ToDecimal(this.tbScoreB.Text);
                IList AnswerList = DoAnswerList(survey.Id);

                CRService.SaveSurvey(App, survey, AnswerList);
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');</script>");
            }
            Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');</script>");
        }
        #endregion

        #region ValidateVisitingSurvey
        private bool ValidateVisitingSurvey()
        {
            foreach (DataGridItem row in this.DG_PartA.Items)
            {
                DropDownList Score = (DropDownList)row.FindControl("Ctrl_ScoreA");
                if (Score.SelectedItem.Value == "0")
                {
                    //GDC.Utility.Web.ImgRequiredFieldValidator validator = (GDC.Utility.Web.ImgRequiredFieldValidator)row.FindControl("ScoreRequired");
                    //validator.Enabled = true;
                    return false;
                }
            }
            return true;
        }
        #endregion

        #region Submit
        void Btn_Submit_Click(object sender, EventArgs e)
        {
            //			if(!ValidateVisitingSurvey())
            //			{
            //				WebUtility.ShowAlert(Page, "You should answer all the questions of Customer Visiting.");
            //				return;
            //			}

            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                BEGDC.CC.Entity.CustomerSurvey survey = BuildCustomerSurvey();
                //				survey.ScoreA = CaculateScoreA(this.DG_PartA);
                //				survey.ScoreB = CaculateScoreB(this.DG_PartB);
                survey.ScoreA = Convert.ToDecimal(this.tbScoreA.Text);
                survey.ScoreB = Convert.ToDecimal(this.tbScoreB.Text);
                IList AnswerList = DoAnswerList(survey.Id);

                CRService.SubmitSurvey(App, survey, AnswerList, string.Empty);

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');</script>");
            }
        }
        #endregion

        #region ButtonStatusSetting
        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;

            this.Btn_Save.Visible = this.Access.IsButtonVisible(CRTransitionList.Save);
            this.Btn_Submit.Visible = this.Access.IsButtonVisible(CRTransitionList.Submit);
            this.Btn_Reply.Visible = this.Access.IsButtonVisible(CRTransitionList.Reply);

            if (Access.IsReadOnly && this.Step != BEGDC.CC.BL.Workflow.WorkTransition.CR_CRSurvey)
            {
                IsFeedbackStep = false;
                BindReadOnlyStatus();
            }
        }
        #endregion

        #region Reply
        void Btn_Reply_Click(object sender, EventArgs e)
        {
            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                CRService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');</script>");
            }
        }
        #endregion
    }
}
